#include "DatabaseMysql.h"

namespace RisingStar
{
	CDatabaseMysql::CDatabaseMysql()
	{
		
	}
	CDatabaseMysql::~CDatabaseMysql()
	{
		
	}
		
		//连接数据库
	bool CDatabaseMysql::Connect(string username,string password,string dataname,string ip,WORD port)
	{		
		mysql_init(&mConn);


		if(!mysql_real_connect(&mConn,ip.c_str(),username.c_str(),password.c_str(),dataname.c_str(),0,NULL,CLIENT_FOUND_ROWS)) //"root":数据库管理员 "":root密码 "test":数据库的名字
		{
			cout<<"Failed to connect to database: Error: %s"<<mysql_error(&mConn)<<endl;
			return false;
		}
		if ( mysql_set_character_set( & mConn, "utf8" ) ) { 
            cout<<"错误:"<< mysql_error( & mConn)<<endl ; 
        } 
		return true;
	}
	//执行数据库操作
	bool CDatabaseMysql::Execute(string sql)
	{		
		if(mysql_real_query(&mConn, sql.c_str(), sql.length()) != 0)
		{
			cout<<"sql:"<<sql<<endl;
			string sMsg = "执行SQL语句失败，失败原因:";
			sMsg += mysql_error(&mConn);
			cout<<sMsg<<endl;
			boost::throw_exception(runtime_error(sMsg));
			return false;
		}
		
		return true;
	}
	//获取详细信息
	bool CDatabaseMysql::Detail(string sql,map<string,string>& detail)
	{
		MYSQL_RES* result;
		MYSQL_ROW row;
		MYSQL_FIELD *field;
		unsigned int num_fields;
		if(mysql_query(&mConn,sql.c_str()))
		{
			cout<<RSTR("错误:")<<sql<<endl;
			return false;
		}
		//deal with the result
		result=mysql_store_result(&mConn);
		
		detail.clear();
		map<int,string> labelInt;
		int i = 0;
		while((field = mysql_fetch_field(result)))
		{
			labelInt[i] = field->name;
			i++;
		}
		
		num_fields = mysql_num_fields(result);		
		
		if(mysql_num_rows(result))
		{
			if((row=mysql_fetch_row(result)))
			{
				for(i = 0; i < num_fields; i++)
				{
					detail[labelInt[i]] = row[i]?row[i]:"";
				}
			}
		}
		//释放资源
		mysql_free_result(result);
		
		return true;
	}
	//查询列表
	bool CDatabaseMysql::SearchList(string sql,list<map<string,string> >& infoList)
	{
		MYSQL_RES* result;
		MYSQL_ROW row;
		MYSQL_FIELD *field;
		unsigned int num_fields;

		if(mysql_query(&mConn,sql.c_str()))
		{
			cout<<RSTR("错误:")<<sql<<endl;
			return false;
		}
		
		//deal with the result
		result=mysql_store_result(&mConn);
		
		infoList.clear();
		map<int,string> labelInt;
		int i = 0;
		while((field = mysql_fetch_field(result)))
		{
			labelInt[i] = field->name;
			i++;
		}
		
		num_fields = mysql_num_fields(result);	
		if(mysql_num_rows(result))
		{
			while((row=mysql_fetch_row(result)))
			{
				map<string,string> detail;
				for(i = 0; i < num_fields; i++)
				{
					detail[labelInt[i]] = row[i]?row[i]:"";
				}
				infoList.push_back(detail);
			}
		}
		
		//release the resource
		mysql_free_result(result);
		return true;
	}
	//关闭连接
	bool CDatabaseMysql::Close()
	{
		mysql_close(&mConn);
		return true;
	}
		

	
};
